<template>
  <div class="short-video-like" @click="handleLike">
    <el-button 
      :type="isLiked ? 'danger' : 'default'" 
      :loading="loading"
      plain
    >
      <svg class="icon" aria-hidden="true" style="width: 1em; height: 1em; vertical-align: middle; fill: currentColor; overflow: hidden;">
        <use :xlink:href="isLiked ? '#i-dianzan' : '#i-quxiaodianzan'"></use>
      </svg>
      {{ isLiked ? '已点赞' : '点赞' }}
      <span v-if="likeCount > 0">({{ likeCount }})</span>
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Star, StarFilled } from '@element-plus/icons-vue'
import { likeShortVideo, unlikeShortVideo } from '@/api/modules/shortVideo'
import type { ShortVideo } from '@/api/modules/shortVideo'

const props = defineProps<{
  video: ShortVideo
}>()

const emit = defineEmits<{
  (e: 'like-change', likeCount: number): void
}>()

// 点赞状态
const isLiked = ref(false)
const likeCount = ref(0)
const loading = ref(false)

// 监听视频数据变化
watch(() => props.video, (newVal) => {
  if (newVal) {
    isLiked.value = newVal.is_liked || false
    likeCount.value = newVal.like_count || 0
  }
}, { immediate: true })

// 处理点赞/取消点赞
const handleLike = async () => {
  if (loading.value || !props.video.video_id) return
  
  loading.value = true
  try {
    if (isLiked.value) {
      // 取消点赞
      await unlikeShortVideo({ video_id: props.video.video_id })
      isLiked.value = false
      likeCount.value = Math.max(0, likeCount.value - 1)
      ElMessage.success('已取消点赞')
    } else {
      // 点赞
      await likeShortVideo({ video_id: props.video.video_id })
      isLiked.value = true
      likeCount.value += 1
      ElMessage.success('点赞成功')
    }
    
    // 触发事件更新父组件数据
    emit('like-change', likeCount.value)
  } catch (error) {
    console.error('点赞操作失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.short-video-like {
  display: inline-block;
  cursor: pointer;
}

.short-video-like .el-button {
  transition: all 0.3s ease;
}
</style>